//
//  QBKlineViewController.swift
//  ZeroShare
//
//  Created by July on 2020/3/21.
//  Copyright © 2020 saeipi. All rights reserved.
//

import UIKit
import SwiftyJSON

class QBKlineViewController: UIViewController {
    
    var selectTopStr = "MA"
    var selectBottomStr = "MACD"
    var selectTimeStr = "5"
    var selectBottomType = KSSeriesKey.macd
    var selectTopType = KSSeriesKey.ma
    //1、k线图
    lazy var chartView: KSKChartView = {
        let chartView      = KSKChartView.init(frame: CGRect.init(x: 0, y: 250, width: self.view.frame.width, height: 388))
        chartView.backgroundColor = UIColor.white
        chartView.delegate = self
        return chartView
    }()
    
    lazy var valueView: KSChartValueView = {
        let valueView = KSChartValueView.init(frame: CGRect.init(x: 0, y: 0, width: self.view.frame.width, height: 44))
        valueView.hiddenKit()
        self.headView.addSubview(valueView)
        return valueView
    }()
    
    lazy var headView: KSHeadView = {
        let headView      = KSHeadView.init(frame: CGRect.init(x: 0, y: 206, width: self.view.frame.width, height: 44))
        headView.backgroundColor = UIColor.white
        headView.myHeadBlock = {
           [weak self] (str,isture) in
            if str == "time" {
                if isture == false {
                    self?.timeMenuView.isHidden = false
                    self?.timeMenuView.timeStr = self?.selectTimeStr ?? ""
                }else{
                    self?.timeMenuView.isHidden = true
                }
            }else{
                if isture == false {
                     self?.zhiBiaoView.isHidden = false
                     self?.zhiBiaoView.selectBottomStr = self!.selectBottomStr
                     self?.zhiBiaoView.selectTopStr = self!.selectTopStr
                }else{
                    self?.zhiBiaoView.isHidden = true
                }
            }
            
           
        }
        return headView
    }()
    
    lazy var zhiBiaoView: KSPullZhiBiaoView = {
        let zhiBiaoView             = KSPullZhiBiaoView.init(frame: CGRect.init(x: KS_Const_Point16, y: 250, width: UIScreen.main.bounds.size.width - KS_Const_Point32, height: 110))
        //timeMenuView.triangleCenterX = (self.headView.leftButton?.center.x)!
        zhiBiaoView.fillColor       = KS_Const_Color_Menu_Background
        zhiBiaoView.strokeColor     = UIColor.ks_rgba(192, 192, 192, 1)
        zhiBiaoView.drawBubble()
        zhiBiaoView.bottomBlock = {
            [weak self] str in
            self?.selectBottomStr = str
            self?.zhiBiaoView.isHidden = true
            self?.headView.typeBool = false
            self?.createBottomZhiBiaoType(type: str)
            
        }
        zhiBiaoView.topBlock = {
            [weak self] str in
            self?.selectTopStr = str
            self?.zhiBiaoView.isHidden = true
            self?.headView.typeBool = false
            self?.createTapZhiBiaoType(type:str)
            
        }
        self.view.addSubview(zhiBiaoView)
        return zhiBiaoView
    }()
    
    lazy var timeMenuView: KSPullView = {
        let timeMenuView             = KSPullView.init(frame: CGRect.init(x: KS_Const_Point16, y: 250, width: UIScreen.main.bounds.size.width - KS_Const_Point32, height: 200))
        //timeMenuView.triangleCenterX = (self.headView.leftButton?.center.x)!
        timeMenuView.fillColor       = KS_Const_Color_Menu_Background
        timeMenuView.strokeColor     = UIColor.ks_rgba(192, 192, 192, 1)
        timeMenuView.drawBubble()
        timeMenuView.timeStr = self.selectTimeStr
        timeMenuView.timeBlock = {
            [weak self] (str,str2) in
            self?.selectTimeStr = str
            self?.timeMenuView.isHidden = true
            self?.headView.timeBool = false
            self?.requestBinanceKlines(time: str)
            self?.headView.leftButton?.setTitle(str2, for: .normal)
        }
        self.view.addSubview(timeMenuView)
        return timeMenuView
    }()
    
     override func viewDidLoad() {
         super.viewDidLoad()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: #selector(getBack))
        self.view.addSubview(self.headView)
        self.view.addSubview(self.chartView)
        self.requestBinanceKlines(time: self.selectTimeStr)
     }
    
    @objc func getBack(){
        self.dismiss(animated: true, completion: nil)
    }
    
    private func createTapZhiBiaoType(type:String){
        if type == "MA" {
            self.selectTopType = KSSeriesKey.ma
        }else if type == "EMA" {
            self.selectTopType = KSSeriesKey.ema
        }else if type == "BOOL" {
            self.selectTopType = KSSeriesKey.boll
        }else if type == "nil" {
            self.selectTopType = ""
        }
        self.changeViewType()
    }
    
    private func createBottomZhiBiaoType(type:String){
        if type == "MACD" {
            self.selectBottomType = KSSeriesKey.macd
        }else if type == "KDJ" {
            self.selectBottomType = KSSeriesKey.kdj
        }else if type == "RSI" {
            self.selectBottomType = KSSeriesKey.rsi
        }else if type == "BOOL" {
            self.selectBottomType = KSSeriesKey.boll
        }else if type == "nil" {
            self.selectBottomType = KSSeriesKey.volume
        }
        self.changeViewType()
    }
    private func changeViewType(){
        self.chartView.chartView.updateSerie(hidden: false, key: self.selectTopType, isMasterCandle: true)
        self.chartView.chartView.updateSerie(hidden: false, key: self.selectBottomType, isMasterCandle: false, index: 1)
        self.chartView.chartView.refreshChart(isAll: self.selectTopType == "" ? false : true, isDraw: true, isChangeTai: true)
    }
    
    //======================================================================
    // MARK: - 13、网络请求
    //======================================================================
    private func requestBinanceKlines(time: String) {
        //清空数据
        if time == "kineLine" {
            self.chartView.chartView.updateSerie(hidden: false, key: KSSeriesKey.timeline, isMasterCandle: false)
            self.chartView.chartView.updateSerie(hidden: false, key: "MACD", isMasterCandle: false, index: 1)
            self.chartView.chartView.refreshChart(isAll: true, isDraw: true, isChangeTai: true)
            
            return
            
        }
        let url = "http://144.34.160.156:8003/v1/md/kline?interval="+time+"&contract_id=1&exchange_id=1&limit=500"
        ASNetManager.request(url: url, parameters: nil, success: { (result: Any?) in
            if let _result = result {
                let jsons = JSON(_result)
                var candles: [KSChartItem] = [KSChartItem]()
                for json in jsons["data"].arrayValue {
                    let info        = KSChartItem()
                    info.time       = json[0].intValue/1000/1000// 开盘时间
                    //json["k"]["T"]// 这根K线的结束时间
                    info.open   = json[1].stringValue// 开盘价
                    info.close   = json[2].stringValue// 最高价
                    info.high    = json[3].stringValue// 最低价
                    info.low  = json[4].stringValue// 收盘价(当前K线未结束的即为最新价)
                    info.volume = json[5].stringValue// 成交量
                    candles.append(info)
                }
                self.chartView.klineData.removeAll()
                self.chartView.resetChart(datas: candles)
                self.chartView.chartView.updateSerie(hidden: false, key: "MA", isMasterCandle: true)
                self.chartView.chartView.updateSerie(hidden: false, key: "MACD", isMasterCandle: false, index: 1)
                self.chartView.chartView.refreshChart(isAll: true, isDraw: true, isChangeTai: true)
            }
        }) { (error: ASRequestError?) in
            
        }
    }
}

extension QBKlineViewController: KSKChartViewDelegate{
    @objc func kchartView(chart: KSKChartView, didSelectAt index: Int, item: KSChartItem){
        self.valueView.update(value: item)
        print("1111")
    }
    @objc func kchartView(chart: KSKChartView, displayCross: Bool){
        
    }
    @objc func kchartViewTouch(chart: KSKChartView){
        
    }
    
    @objc func kchartViewTouchLong(chart: KSKChartView,type:String){
        if type == "start" {
            self.valueView.showKit()
        }else if type == "end"{
            self.valueView.hiddenKit()
        }
    }
}
